import React, { Component } from 'react';
import { connect } from 'dva';

import { Form } from '@ant-design/compatible';

import {
  Card,
  Col,
  Input,
  InputNumber,
  Row,
  Badge,
} from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1430304_y2xsdrlvrh.js',
});

interface HardwareProductProps {
  detail?: any;
  forms: any;
  mergeFun: (name: string, value: any) => void;
}

interface HardwareProductState {
  detail_list: object;
  prev_detail_list: object;
  advance_percent: number;
  deliver_percent: number;
  final_percent: number;
}

function mapStateToProps(state: any) {
  const {
    franchiseeContractEditor: { detail, contractTypeDetail, partnersAndSubject },
  } = state;

  return {
    detail,
    contractTypeDetail,
    partnersAndSubject,
  };
}

@connect(mapStateToProps)

class HardwareProductElem extends Component<HardwareProductProps, HardwareProductState> {
  state = {
    detail_list: [
      {
        id: 0,
        cargo: '',
        brand: '',
        version: '',
        detail_count: 0,
        count: 0,
        unit_price: 0,
        total_price: 0,
      },
    ],
    prev_detail_list: [],
    advance_percent: 0,
    deliver_percent: 0,
    final_percent: 0,
  };

  static getDerivedStateFromProps(nextProps: HardwareProductProps, preState: HardwareProductState) {
    const {
      detail: {
        detail_list,
        total_amount,
        advance_percent,
        deliver_percent,
        final_percent,
      },
      mergeFun,
    } = nextProps;

    if (detail_list && detail_list !== preState.prev_detail_list) {
      mergeFun('total_amount', total_amount);

      const new_detail_list = detail_list.map((item: any) => {
        const { unit_price, total_price } = item;
        const new_item = { ...item };

        new_item.unit_price = unit_price / 100;
        new_item.total_price = total_price / 100;
        return new_item;
      });
      mergeFun('detail_list', JSON.stringify(new_detail_list));

      return {
        detail_list: new_detail_list,
        prev_detail_list: detail_list,
        advance_percent: total_amount * advance_percent / 100,
        deliver_percent: total_amount * deliver_percent / 100,
        final_percent: total_amount * final_percent / 100,
      };
    }

    return null;
  }

  changeForms = (index: any, changeType: string, value: any) => {
    value = typeof (value) === 'object' && value ? value.target.value : value;
    if (value) {
      this.change_detail_list(index, value, changeType);
    }
  }

  change_detail_list = (index: any, value: any = 0, changeType: any) => {
    const { detail_list } = this.state;
    const new_detail_list = detail_list.map(item => ({ ...item }));

    new_detail_list[index][changeType] = value;
    this.setState({
      detail_list: new_detail_list,
    }, () => {
      this.calculateResults(index);
    });
  }

  calculateResults = (index?: number | any) => {
    const { detail_list } = this.state;
    const { mergeFun, forms: { getFieldsValue } } = this.props;
    const new_detail_list = detail_list.map((item) => ({ ...item }));

    if (typeof index === 'number') {
      const { count, unit_price } = new_detail_list[index];
      new_detail_list[index].total_price = count * unit_price;
    }
    this.setState({
      detail_list: new_detail_list,
    }, () => {
      const total_fee: any = new_detail_list.reduce((origin: any, target: any) => (
        origin + target.total_price
      ), 0);

      const returnValues = getFieldsValue([
        'advance_percent',
        'deliver_percent',
        'final_percent',
      ]);

      this.setState({
        advance_percent: total_fee * returnValues.advance_percent || 0,
        deliver_percent: total_fee * returnValues.deliver_percent || 0,
        final_percent: total_fee * returnValues.final_percent || 0,
      }, () => {
        mergeFun('total_amount', total_fee * 100);
        mergeFun('detail_list', JSON.stringify(new_detail_list));
      });
    });
  }

  handleValidation = () => {
    // const { forms: { getFieldsValue } } = this.props;
    // const returnValues = getFieldsValue([
    //   'advance_percent',
    //   'deliver_percent',
    //   'final_percent',
    // ]);
  }

  // 添加批次
  handleAddOrder = () => {
    const { detail_list } = this.state;
    const { mergeFun } = this.props;
    const new_detail_list = detail_list.map((item, index) => ({ ...item }));

    new_detail_list.push({
      id: new_detail_list[new_detail_list.length - 1].id + 1,
      cargo: '',
      brand: '',
      version: '',
      detail_count: 0,
      count: 0,
      unit_price: 0,
      total_price: 0,
    });

    this.setState({ detail_list: new_detail_list }, () => {
      this.calculateResults();
      mergeFun('detail_list', JSON.stringify(new_detail_list));
    });
  }

  // 删除批次
  handleDeleteOrder = (index: number) => {
    const { detail_list } = this.state;
    const { mergeFun } = this.props;
    const new_detail_list = detail_list.map(item => ({ ...item }));
    const { forms: { resetFields } } = this.props;
    resetFields(['cargo', 'brand', 'version', 'detail_count', 'count', 'unit_price', 'total_price']);

    new_detail_list.splice(index, 1);

    new_detail_list.map((item, key) => ({ ...item }));

    this.setState({ detail_list: new_detail_list }, () => {
      this.calculateResults();
      mergeFun('detail_list', JSON.stringify(new_detail_list));
    });
  }

  renderSalesDetailElem = () => {
    const { detail_list } = this.state;
    const { forms: { getFieldDecorator } } = this.props;
    const clos: any[] = [];

    detail_list.map((item: any, index: number) => {
      const addElem = (
        <Col span={24} key={item.id}>
          <div style={{
            marginBottom: index === detail_list.length - 1 ? 0 : 20,
          }}
          >
            <div style={{ display: 'flex' }}>
              <div
                style={{
                  marginRight: 8,
                  width: 56,
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                }}
              >
                <Badge
                  count={index + 1}
                  style={{
                    backgroundColor: 'rgba(0,0,0,0.09)',
                    color: '#000',
                    fontWeight: 'bold',
                  }}
                />
                <div
                  className="operLink marginT12"
                  onClick={this.handleAddOrder.bind(this, index)}
                >
                  <MyIcon type="iconjiahao" style={{ margin: '4px 4px 0 0' }} />
                  增加
                </div>
                {index !== 0 && (
                  <div
                    style={{ color: '#ff4d4f' }}
                    className="operLink marginT24"
                    onClick={this.handleDeleteOrder.bind(this, index)}
                  >
                    <MyIcon type="iconjianhao" style={{ margin: '4px 4px 0 0' }} />
                    删除
                  </div>
                )}
              </div>
              <div className="tableListForm dottedBox" style={{ flex: 1 }}>
                <Row gutter={12}>
                  <Col md={3} sm={24} className="marginB12">
                    <Form.Item label="品牌" className="disBlockImport">
                      {getFieldDecorator(`brand[${index}]`, {
                        initialValue: item.brand,
                        rules: [{ required: true, message: '请输入品牌' }],
                      })(
                        <Input
                          allowClear
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          onChange={this.changeForms.bind(this, index, 'brand')}
                        />,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={5} sm={24} className="marginB12">
                    <Form.Item label="货物名称" className="disBlockImport">
                      {getFieldDecorator(`cargo[${index}]`, {
                        initialValue: item.cargo,
                        rules: [{ required: true, message: '请输入货物名称' }],
                      })(
                        <Input
                          allowClear
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          onChange={this.changeForms.bind(this, index, 'cargo')}
                        />,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={4} sm={24} className="marginB12">
                    <Form.Item label="型号" className="disBlockImport">
                      {getFieldDecorator(`version[${index}]`, {
                        initialValue: item.version,
                        rules: [{ required: true, message: '请输入型号' }],
                      })(
                        <Input
                          allowClear
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          onChange={this.changeForms.bind(this, index, 'version')}
                        />,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={3} sm={24} className="marginB12">
                    <Form.Item label="格口数量(个)" className="disBlockImport">
                      {getFieldDecorator(`detail_count[${index}]`, {
                        initialValue: item.detail_count,
                        rules: [{ required: true, message: '请输入格口数量' }],
                      })(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          min={0}
                          onChange={this.changeForms.bind(this, index, 'detail_count')}
                        />,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={3} sm={24} className="marginB12">
                    <Form.Item label="柜体数量(台)" className="disBlockImport">
                      {getFieldDecorator(`count[${index}]`, {
                        initialValue: item.count,
                        rules: [{ required: true, message: '请输入柜体数量' }],
                      })(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          min={0}
                          onChange={this.changeForms.bind(this, index, 'count')}
                        />,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={3} sm={24} className="marginB12">
                    <Form.Item label="单价(元)" className="disBlockImport">
                      {getFieldDecorator(`unit_price[${index}]`, {
                        initialValue: item.unit_price,
                        rules: [{ required: true, message: '请输入单价' }],
                      })(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          min={0}
                          onChange={this.changeForms.bind(this, index, 'unit_price')}
                        />,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={3} sm={24} className="marginB12">
                    <Form.Item label="小计(元)" className="disBlockImport">
                      {getFieldDecorator(`total_price[${index}]`, {
                        initialValue: item.total_price,
                        rules: [{ required: false, message: '请输入时间' }],
                      })(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder="请输入"
                          disabled
                        />,
                      )}
                    </Form.Item>
                  </Col>
                </Row>
              </div>
            </div>
          </div>
        </Col>
      );
      return clos.push(addElem);
    });

    return (
      <Card title="销售明细" bordered={false} className="paddingB10">
        <Row gutter={12}>
          {clos}
        </Row>
      </Card>
    );
  };

  renderPaymentInfoElem = () => {
    const {
      advance_percent,
      deliver_percent,
      final_percent,
    }: any = this.state;
    const { forms: { getFieldDecorator }, detail } = this.props;

    return (
      <Card title="付款信息" bordered={false}>
        <Row gutter={8}>
          <Col md={8} sm={24}>
            <Form.Item label="预付款" colon={false}>
              {getFieldDecorator('advance_percent', {
                initialValue: detail.advance_percent,
                rules: [{ required: true, message: '请输入预付款' }],
              })(
                <Input
                  allowClear
                  type="number"
                  suffix="%"
                  style={{ width: '100%' }}
                  placeholder="请输入"
                  onChange={this.calculateResults}
                  onBlur={this.handleValidation}
                />,
              )}
              <span className="marginL16" style={{ lineHeight: '32px' }}>{advance_percent / 100}</span>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={8}>
          <Col md={8} sm={24}>
            <Form.Item label="发货款" colon={false}>
              {getFieldDecorator('deliver_percent', {
                initialValue: detail.deliver_percent,
                rules: [{ required: true, message: '请输入发货款' }],
              })(
                <Input
                  allowClear
                  type="number"
                  suffix="%"
                  style={{ width: '100%' }}
                  placeholder="请输入"
                  onChange={this.calculateResults}
                  onBlur={this.handleValidation}
                />,
              )}
              <span className="marginL16" style={{ lineHeight: '32px' }}>{deliver_percent / 100}</span>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={8}>
          <Col md={8} sm={24}>
            <Form.Item label="　尾款" colon={false}>
              {getFieldDecorator('final_percent', {
                initialValue: detail.final_percent,
                rules: [{ required: true, message: '请输入尾款' }],
              })(
                <Input
                  allowClear
                  type="number"
                  suffix="%"
                  style={{ width: '100%' }}
                  placeholder="请输入"
                  onChange={this.calculateResults}
                  onBlur={this.handleValidation}
                />,
              )}
              <span className="marginL16" style={{ lineHeight: '32px' }}>{final_percent / 100}</span>
            </Form.Item>
          </Col>
        </Row>
      </Card>
    );
  };

  render() {
    return (
      <div>
        {this.renderSalesDetailElem()}
        {this.renderPaymentInfoElem()}
      </div>
    );
  }
}

export default HardwareProductElem;
